﻿/// <reference path="RemoteKmDb.js"/>
/// <reference path="BrowserKmDb.js"/>
/// <reference path="LoadLocal.js"/>
/// <reference path="jquery-1.5-vsdoc.js"/>
/// <reference path="jquery.json.js"/>
/// <reference path="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.js"/>
/// <reference path="Helper.js"/>
/// <reference path="Params.js"/>

// BUILD DATABASE ----------------------------------------------
var db;

try {
    if (window.openDatabase) {
        db = openDatabase("JSC.Mobile", "1.0", "JSC.Mobile HTML5 Database", 200000);
        if (!db)
            alert("Failed to open the database on disk.  This is probably because the version was bad or there is not enough space left in this domain's quota");
        else
			var hideDelete = true;
    } else
        alert("Couldn't open the database.  Please try with a WebKit nightly with this feature enabled");
} catch(err) {

}

function deleteItAll() {
    db.transaction(function (tx) {
        tx.executeSql("DELETE FROM Kilometers",
            [],
            null,
            errorMessage
        );
    });
}

// BUILD TABLE -------------------------------------------------

function loadOrCreateKilometers(loadDelegate)
{
    db.transaction(function(tx) {
        tx.executeSql("SELECT COUNT(*) FROM Kilometers", [], loadDelegate, function(tx, error) {
            tx.executeSql("CREATE TABLE Kilometers (id INTEGER PRIMARY KEY, datum NUMERIC, startkm INTEGER, eindkm INTEGER, omschrijving TEXT, synchronisatiemoment NUMERIC, remoteid INTEGER, state INTEGER)", 
                [], loadDelegate);
        });
    });
}

// NEW ----------------------------------------------------------

function newLocalKm(datum, startkm, eindkm, omschrijving, synchronisatiemoment, remoteid, state, succesCallback){
    db.transaction(function (tx) {
        tx.executeSql("INSERT INTO Kilometers (id, datum, startkm, eindkm, omschrijving, synchronisatiemoment, remoteid, state) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)",
            [datum, startkm, eindkm, omschrijving, synchronisatiemoment, remoteid, state],
            function (tx, result) {
                if (succesCallback)
                    succesCallback();
            },
            errorMessage
        );
    });
}

function syncLocalKm(datum, startkm, eindkm, omschrijving, synchronisatiemoment, remoteid) {
    db.transaction(function (tx) {
        tx.executeSql("SELECT COUNT(*) Aantal FROM Kilometers WHERE remoteid = ?",
            [remoteid],
            function (tx, data) {
                var doSync = false;
                if (data.rows.length > 0) {
                    var row = data.rows.item(0);
                    doSync = (row["Aantal"] == 0);
                }
                if (doSync) {
                    newLocalKm(datum, startkm, eindkm, omschrijving, synchronisatiemoment, remoteid, LocalRecordState.Unchanged, null); // sync it locally
                }
            },
            errorMessage
        );
    });
}

function setLocalKilometerInSync(localid, remoteid, synchronisatiemoment) {
    db.transaction(function (tx) {
        tx.executeSql("UPDATE Kilometers SET remoteid = ?, synchronisatiemoment = ?, state = ? WHERE id= ?",
            [remoteid, synchronisatiemoment, LocalRecordState.Unchanged, localid],
            null,
            errorMessage);
    });
}


function addKilometerSimple() {
    var omschrijving = $("#select-omschrijving").val();
    var eindkm = $("#eindkm").val();
    if (omschrijving == "new-omschrijving") {
        omschrijving = $("#omschrijving").val();
    }

    db.transaction(function (tx) {
        tx.executeSql("SELECT eindkm FROM Kilometers WHERE state <> ? ORDER BY eindkm DESC LIMIT 1",
            [LocalRecordState.Deleted],
            function (tx, data) {
                var vorigKm = 0;
                if (data.rows.length > 0) {
                    var row = data.rows.item(0);
                    vorigKm = row.eindkm;
                }
                newLocalKm(Date(), vorigKm, eindkm, omschrijving, null, null, LocalRecordState.New, LoadListView); //add it locally sync 
            },
            errorMessage
        );
    });    
}

function GetLocalSyncableKilometers(syncAction) {
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM Kilometers",
            [],
            function (tx, result) {
                for (var i = 0; i < result.rows.length; ++i) {
                    var row = result.rows.item(i);

                    if (syncAction)
                        syncAction(row);
                }
            },
            errorMessage);
    });
}


// DELETE ----------------------------------------------------------

function deleteLocalKm(id, remoteid, successCallback) {
    db.transaction(function (tx) {
        if (remoteid == null) {
            tx.executeSql("DELETE FROM Kilometers WHERE id= ?",
                [id],
                successCallback,
                errorMessage);
        }
        else {
            tx.executeSql("UPDATE Kilometers SET state = ? WHERE remoteid= ?",
                [LocalRecordState.Deleted, remoteid],
                successCallback,
                errorMessage);
        }
    });
}

// UPDATE ----------------------------------------------------------

function updateLocalKm(id, omschrijving, datum, beginkm, eindkm, state, succesCallback) {
    db.transaction(function (tx) {
        tx.executeSql("UPDATE Kilometers SET state = ?, omschrijving = ?, datum = ?, startkm = ?, eindkm = ? WHERE id= ?",
            [state, omschrijving, datum, beginkm, eindkm, id],
            succesCallback,
            errorMessage);
    });
}

// BUILD LIST ---------------------------------------------------

function BuidList(container){
    $(container).html("");

    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM Kilometers WHERE state <> ? ORDER BY date(datum), startkm desc, eindkm desc",
            [LocalRecordState.Deleted],
            function (tx, result) {
                var kilometers = SQLResultSetRowListToArray(result);
                var groep = {}
                $.each(kilometers, function (i, m) {
                    var d = new Date(m.datum).toLocaleDateString();
                    if (!groep[d])
                        groep[d] = [m];
                    else
                        groep[d].push(m);
                });

                $("#kmListItemTemplate").tmpl(groep).appendTo(container);
                $(container).listview("refresh");
            },
            errorMessage);
    });
}

function NavigateToKilometerEdit(id) {
    var x = String.format("{0}/KilometerRegistratie/Edit", BASE_URL);
    NavigateTo(x, "editid", id);
}

function NavigateToKilometerDelete(id) {
    var x = String.format("{0}/KilometerRegistratie/Delete", BASE_URL);
    NavigateTo(x, "deleteid", id);
}

function BuildOmschrijvingSelect() {
    db.transaction(function (tx) {
        tx.executeSql("SELECT DISTINCT omschrijving id, omschrijving FROM Kilometers UNION ALL SELECT 'new-omschrijving' id, 'Nieuwe omschrijving' omschrijving",
            [],
            function (tx, result) {
                var omschrijvingen = SQLResultSetRowListToArray(result);
                $("#omschrijvingSelectTemplate").tmpl(omschrijvingen).appendTo("#select-omschrijving");
                $("#select-omschrijving").trigger("change");

                /// een jqm selectmenu click actie kun je koppelen door de id select container plus "-menu", bijv: "#select-omschrijving-menu"
                $("#select-omschrijving-menu").click(OmschrijvingSelectionChanged);
                OmschrijvingSelectionChanged();
            },
            errorMessage);
    }); 
}

function OmschrijvingSelectionChanged() {
    if ($("#select-omschrijving").val() == "new-omschrijving") {
        $("#add-omschrijving").show("fast", function () {
            $("input:text:visible:last").focus();
            $("input:text:visible:first").focus();
        });
    }
    $("input:text:visible:last").focus();
    $("input:text:visible:first").focus();
}

function LoadEditKmDetails() {
    var id = localStorage.editid; 
    
    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM Kilometers WHERE id = ?",
        [id],
        function (tx, result) {
            // jquery templates in combination with jquerymobile (1 beta 3) doesn't work great together that's why I did it on an dirty way
            var row
            if (result.rows.length == 0)
                return;
            row = result.rows.item(0);
            $("#edit-key").val(row.id);
            $("#edit-omschrijving").val(row.omschrijving);
            $("#edit-startkm").val(row.startkm);
            $("#edit-eindkm").val(row.eindkm);
            $("#edit-datum").val(toSimpleDateString(row.datum));

            $("#edit-beginkm").numeric();
            $("#edit-eindkm").numeric();
            $("#edit-datum").mask("99-99-9999");
            $("#btnDelete").attr("href", String.format("javascript:NavigateToKilometerDelete({0})", row.id));
        },
        errorMessage);
    });
}

function LoadDeleteKmDetails() {
    var id = localStorage.deleteid; 

    db.transaction(function (tx) {
        tx.executeSql("SELECT * FROM Kilometers WHERE id = ?",
        [id],
        function (tx, result) {
            var row
            if (result.rows.length == 0)
                return;
            row = result.rows.item(0);

            $("#kmTemplate").tmpl(row).appendTo("#result");

            // jquerymobile has troubles with refreshing the page that's why the cancel button is altered this way
            var href = String.format("javascript:NavigateToKilometerEdit({0})", row.id);
            $("#cancel").attr("href", href);
        },
        errorMessage);
    });
}

function UpdateKm() {
    var datum = toSimpleDate($("#edit-datum").val());
    updateLocalKm(
        $("#edit-key").val(),
        $("#edit-omschrijving").val(),
        datum,
        $("#edit-startkm").val(),
        $("#edit-eindkm").val(),
        LocalRecordState.Updated,
        null);
    // if you run the redirectToHome as an successCallback in the updateLocalKm, then the update will rollback. Therefore the underlying hack
    // Asume that the update is commited within 500ms
    setTimeout(redirectToHome, 500);
}

function redirectToHome() {
    window.location.href = String.format("{0}/KilometerRegistratie", BASE_URL);
}

function verwijderLocalKm() {
    var id = $("#delete-key").val();
    var remoteid = $("#delete-key2").val();
    if (id == null)
        return;
    deleteLocalKm(id, remoteid, null);
    // if you run the redirectToHome as an successCallback in the deleteLocalKm, then the delete will rollback. Therefore the underlying hack
    // Asume that the delete is commited within 500ms
    setTimeout(redirectToHome, 500);
}

function LoadListView() {
    BuidList("#result");
    BuildOmschrijvingSelect();
}